const { Model, Schema } = require('../helps/model');
// const { executor } = require('../helps/model');
// CREATE TABLE `manager` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `username` varchar(255)  NOT NULL DEFAULT "" COMMENT '用户名',
//   `password` varchar(255) NOT NULL DEFAULT "" COMMENT '密码',
//   `role_id` int(11) NOT NULL DEFAULT 0 COMMENT '角色id',
//   `status` varchar(255) NOT NULL DEFAULT 1 COMMENT '状态：0，禁用；1，启用',
//   `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='管理员表';

/**
 * 格式化密码
 * @param password
 * @return {string}
 */
function formatPassword(password = '') {
  return `${password.md5()}${password}`.md5();
}

const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'username', 'password', 'role_id', 'status'],
  default: {
    role_id: 0,
    status: 1,
  },
});

/**
 * 判断密码是否一致
 * @param password
 * @return {boolean}
 */
schema.methods.validatePassword = function (password) {
  console.log(formatPassword(password));
  return this.password === formatPassword(password);
};

export const model = new Model('manager', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add({ username, password, role_id, status }) {
  return model.insert({
    username,
    password: formatPassword(password),
    role_id,
    status,
  });
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, { username, password, role_id, status }) {
  return model.updateByKey(id, {
    username,
    password: formatPassword(password),
    role_id,
    status,
  });
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 修改密码
 * @param id
 * @returns {*}
 */
export function editPassword(id, password) {
  return model.updateByKey(id, {
    password: formatPassword(password),
  });
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

export function findUsername(username) {
  return model.one({
    where: [
      ['username', '=', username],
    ],
  });
}
